//
//  UIImage+asyncDraw.swift
//  ALSinaWeiBoSwift
//
//  Created by 柴瑞军 on 16/4/19.
//  Copyright © 2016年 myCompany. All rights reserved.
//

import UIKit
//异步绘制图片

extension UIImage{
    
    func al_AsyncDrawImage(var size:CGSize?,bgColor : UIColor? = UIColor.whiteColor(),isCorner:Bool = false ,drawFinish:(image:UIImage)->()){

        dispatch_async(dispatch_get_global_queue(0, 0)) {
            let starttime = CACurrentMediaTime()
            //先判断图片有没有传进来尺寸
            if size == nil{
            size  = self.size
            }
            
            //绘制的上下文的rect
            let rect = CGRect(origin: CGPointZero, size: size!)
            
            //开启图形上下文
            
            UIGraphicsBeginImageContextWithOptions(size!, bgColor != nil, UIScreen.mainScreen().scale)
            //设置背景颜色
            bgColor?.setFill()
            
            //填充
            UIRectFill(rect)
            
            //判断是否需要绘制圆角
            if isCorner{
            //绘制圆角
                let path = UIBezierPath(ovalInRect: rect)
                
                path.addClip()
            }
            
            self.drawInRect(rect)
            
            //获取图片
            let image = UIGraphicsGetImageFromCurrentImageContext()
            //结束图片上下文
            UIGraphicsEndImageContext()
            
            //打印出测试时间
            let endtime = CACurrentMediaTime()
//            print("\(endtime)-\(starttime)")
            //返回绘制好的图片
            dispatch_sync(dispatch_get_main_queue(), { 
                drawFinish(image: image)
            })
        }
        
    }
}
